package com.atguigu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.DWDStaticConstants;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author:GaoFei
 * @Description:
 * @Date:Created in 18:11
 * @Modified By:
 */
public class DimUtil {
    public static JSONObject obtainJson(Connection connection, String table, String id) throws Exception {
        String sql = "select * from " + DWDStaticConstants.HBASE_SCHEMA + "." + table + " where id = '" + id + "'";
        // 读取更新时长
        String key = "DIM:" + table + ":" + id;
        Jedis jedis = JedisPoolUtil.getJedis();
        String res = jedis.get(key);
        if (res != null){
            jedis.expire(key,24 * 60 *60);
            jedis.close();
            return JSON.parseObject(res);
        }
        List<JSONObject> result = JDBCUtil.query(connection, sql, JSONObject.class, false);
        jedis.set(key,result.get(0).toJSONString());
        jedis.expire(key,24 * 60 * 60);
        jedis.close();
        return result.get(0);
    }

    public static void deleteRedisKey(String key){
        Jedis jedis = JedisPoolUtil.getJedis();
        jedis.del(key);
        jedis.close();
    }

    // 测试读取速度，计算运行时间
//    public static void main(String[] args) throws Exception {
//        Class.forName(DWDStaticConstants.HBASE_PHOENIX_DRIVER);
//        Connection connection = DriverManager.getConnection(DWDStaticConstants.HBASE_PHOENIX_SERVER);
//        long l1 = System.currentTimeMillis();
//        JSONObject dim_user_info = obtainJson(connection, "DIM_USER_INFO", "997");
//        long l2 = System.currentTimeMillis();
//        JSONObject dim_user_info1 = obtainJson(connection, "DIM_USER_INFO", "997");
//        long l3 = System.currentTimeMillis();
//        JSONObject dim_user_info2 = obtainJson(connection, "DIM_USER_INFO", "997");
//        long l4 = System.currentTimeMillis();
//        System.out.println(l2-l1);
//        System.out.println(l3-l2);
//        System.out.println(l4-l3);
//        connection.close();
//    }
}
